package org.agent.aigccore.core.service.user;

import org.agent.aigccore.model.po.UserInfoPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Component
@Order(1)
public class InitAdminUserRunner implements CommandLineRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(InitAdminUserRunner.class);
    
    @Resource
    private UserService userService;
    
    @Value("${app.init.admin.username:admin}")
    private String adminUsername;
    
    @Value("${app.init.admin.password:admin123}")
    private String adminPassword;
    
    @Value("${app.init.admin.email:admin@example.com}")
    private String adminEmail;
    
    @Value("${app.init.admin.name:系统管理员}")
    private String adminName;
    
    @Override
    public void run(String... args) throws Exception {
        logger.info("开始检查并初始化管理员账号...");
        
        // 检查是否已存在管理员账号
        UserInfoPO existingUser = userService.loadByUsername(adminUsername);
        if (existingUser != null) {
            logger.info("管理员账号 {} 已存在，无需初始化", adminUsername);
            return;
        }
        
        // 创建管理员账号
        UserInfoPO adminUser = new UserInfoPO();
        adminUser.setUserId(UUID.randomUUID().toString());
        adminUser.setUsername(adminUsername);
        adminUser.setPassword(adminPassword);
        adminUser.setEmail(adminEmail);
        adminUser.setName(adminName);
        adminUser.setStatus("NORMAL");
        adminUser.setRole("ADMIN");
        adminUser.setGmtCreate(new Date());
        adminUser.setGmtModified(new Date());
        
        int result = userService.insert(adminUser);
        if (result > 0) {
            logger.info("管理员账号 {} 初始化成功", adminUsername);
        } else {
            logger.error("管理员账号 {} 初始化失败", adminUsername);
        }
    }
}